package com.ray.util.picUtil;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;

public class PicUtils {
	
	/**
	 * 压缩图片并utf编码 获取base64
	 * @param request
	 * @param address
	 * @param picUrl
	 * @param thumWidth
	 * @param thunHeight
	 * @param picFormat
	 * @return
	 * @throws IOException
	 */
	public static String getBase64EncodeUTF8(HttpServletRequest request , String address , String picUrl ,int thumWidth ,int thunHeight , String picFormat) throws IOException {
		ServletContext sc = request.getSession().getServletContext();  
        // 上传位置  
        String path = sc.getRealPath("/") + "/"; // 设定文件保存的目录  
        File ff = new File(path);  
        path=ff.getParent()+address+"/";
        File f = new File(path);  
        if (!f.exists())  
            f.mkdirs(); 
        String newFileName = UUID.randomUUID().toString() ;  
        URL url = new URL(picUrl);  
        Thumbnails.of(url).size(thumWidth, thunHeight)
        //.rotate(90)
        //.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("watermark.png")), 0.5f)
        .outputQuality(0.8f)
        .toFile(new File(path + newFileName + picFormat));
        String base64Str = "data:image/jpeg;base64,"+ImageUtils.image2Base64ForLocal(path + newFileName + picFormat);
        return URLEncoder.encode(base64Str, "UTF-8");
	}
	
	
	public static void main(String[] args) throws IOException {
		/*Thumbnails.of(new File("C:\\\\\\\\Users\\\\\\\\Administrator\\\\\\\\Desktop\\\\\\\\1.jpg"))
        .size(160, 160)
        //.rotate(90)
        //.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("watermark.png")), 0.5f)
        .outputQuality(0.8f)
        .toFile(new File("C:\\\\Users\\\\Administrator\\\\Desktop\\\\2.jpg"));*/
		
        URL url = new URL("https://upload.shinehao.com.cn/202003051041501.jpg");  
		Thumbnails.of(url).size(600, 600)
        //.rotate(90)
        //.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("watermark.png")), 0.5f)
        .outputQuality(0.8f)
        .toFile(new File("C:\\\\Users\\\\Administrator\\\\Desktop\\\\5.png"));
		
		
		
		System.out.println("data:image/jpeg;base64,"+ImageUtils.image2Base64("C:\\Users\\Administrator\\Desktop\\5.jpg"));;
	
		
	}
}
